import log from "./logger";
import * as mssql from "mssql";
import {NodeCO, TrainAllCO} from "./interface";
import config from "./config";
import sender from "./sender";

class HongdonghaoqiangTrainWorker {
    init() {
        this.collection().catch((e) => {
            log.info(e);
        });
        setInterval(() => {
            this.collection().catch((e) => {
                log.info(e);
            });
        }, 1000 * 60)
    }

    async collection() {
        const cfg = {
            user: 'hlsk',
            password: 'hlsk1234',
            server: '130.133.139.163',
            database: 'Train',
            port: 1433,
            options: {
                encrypt: false,
            }
        };
        await mssql.connect(cfg);
        try {
            let startIndex = config.startIndex;
            if (!startIndex || startIndex < 0) {
                startIndex = 0;
            }
            // 设置有效数据查询数量，用于遗漏数据同步
            let queryTotal = config.queryTotal;
            if (!queryTotal || queryTotal < 1) {
                queryTotal = 1;
            }
            let nodes: NodeCO[] = []
            let train_query_sql = "select top 50 CCXX_KEY, CCXX_CCBH, CCXX_CCSJ, CCXX_START, CCXX_END, CCXX_ZCPS, CCXX_ZEDZ, CCXX_ZSJZ, CCXX_ZWCS, CCXX_XM01, CCXX_XM02, MQSJC" +
                " from CCXX ORDER BY MQSJC DESC"
            const train_res = await new mssql.Request().query(train_query_sql);
            let length = train_res.recordset.length;
            if (length <= 0 || length - 1 < startIndex) {
                return;
            }
            // 已查询数量
            let queriedTotal = 0;
            for (let i = startIndex; i < length; i++) {
                if (queriedTotal >= queryTotal) {
                    break;
                }
                let train_data = train_res.recordset[i];
                let train_node_query_sql = "select CPXX_KEY,CPXX_PZR,CPXX_CXLX,CPXX_ID,CPXX_CPXH,CPXX_CPBH,CPXX_EDZZ,CPXX_SJZZ,CPXX_ZCWC,CPXX_ZCSJ,MQSJC" +
                    " from CPXX where CPXX_CCKEY = '" + train_data['CCXX_KEY'] + "' ORDER BY CPXX_ID";
                const train_node_res = await new mssql.Request().query(train_node_query_sql);
                // 总节数小于40的过滤
                if (train_node_res.recordset.length <= 40) {
                    continue;
                }
                for (let i = 0; i < train_node_res.recordset.length; i++) {
                    let train_node_data = train_node_res.recordset[i]
                    nodes.push({
                        centerDeviation: "",
                        frontBackDiff: "",
                        diffWeight: train_node_data['CPXX_ZCWC'],
                        code: train_data['CCXX_KEY'] + '-' + train_node_data['CPXX_ID'] + 1,
                        lable: null,
                        maxNetWeight: train_node_data['CPXX_EDZZ'],
                        no: train_node_data['CPXX_CPBH'],
                        sort: train_node_data['CPXX_ID'] + 1,
                        speed: null,
                        standardTareWeight: null,
                        time: train_data['CCXX_CCSJ'] + ' ' + train_node_data['CPXX_ZCSJ'],
                        trainCode: train_data['CCXX_KEY'],
                        carType: train_node_data['CPXX_CPXH'],
                        weight: train_node_data['CPXX_SJZZ'],
                        containerNumber1: null,
                        containerNumber2: null,
                        containerType1: null,
                        containerType2: null,
                        state: 'Done',
                        createTenantId: null,
                        createTenantName: null
                    });
                }
                log.info("nodes[0]:", nodes[0]);
                // 集装箱类型默认载重32吨，数据库数据不是准确重量
                let totalMaxWeight = 0;
                let wagonType = /^(JSBU|TBBU|TBJU|CICU)$/.test(nodes[0].carType) ? "Container" : "Gondola";
                if ("Container" === wagonType) {
                    for (let i = 0; i < nodes.length; i++) {
                        let node = nodes[i];
                        node["maxNetWeight"] = 32;
                    }
                    totalMaxWeight = 32 * nodes.length;
                } else {
                    totalMaxWeight = train_data['CCXX_ZEDZ'];
                }
                // 时间存在中文解析错误的情况
                let startTime = nodes[0]['time'];
                if (startTime) {
                    startTime.replace(new RegExp("[：；;]", "gm"), ":");
                }
                let endTime = nodes[nodes.length - 1]['time'];
                if (endTime) {
                    endTime.replace(new RegExp("[：；;]", "gm"), ":");
                }
                let totalWeight = train_data['CCXX_ZSJZ'];
                let train: TrainAllCO = {
                    wagonType: wagonType,
                    firstNo: nodes[0].no,
                    lastNo: nodes[nodes.length - 1].no,
                    type: "db",
                    totalDiffWeight: totalWeight - totalMaxWeight,
                    totalMaxWeight: totalMaxWeight,
                    totalWeight: totalWeight,
                    boxCount: null,
                    code: train_data['CCXX_KEY'],
                    deviceName: config.deviceName,
                    direction: "Leave",
                    name: train_data['CCXX_CCBH'],
                    no: train_data['CCXX_CCBH'],
                    nodes: nodes,
                    platformId: config.platformId,
                    platformName: config.platformName,
                    productName: train_data['CCXX_XM01'],
                    senderName: null,
                    startTime: startTime,
                    endTime: endTime,
                    stationName: train_data['CCXX_XM02'],
                    time: train_data['MQSJC'],
                    totalNode: nodes.length,
                    createTenantId: null,
                    createTenantName: null,
                }
                // log.info("train:", train);
                try {
                    await sender.send("trainAll", train);
                    nodes = []
                } catch (e) {
                    log.error("err train:", e);
                }
                queriedTotal += 1;
            }
        } catch (e) {
            log.error(e);
        }
    }
}

const hongdonghaoqiangTrainWorker = new HongdonghaoqiangTrainWorker();
export default hongdonghaoqiangTrainWorker;